package com.ns.school.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.school.po.sys.Menu;
import com.ns.school.po.edu.ShowMenuVo;
import com.ns.school.mapper.sys.MenuMapper;
import com.ns.school.service.sys.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<ShowMenuVo> getShowMenuByUser(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", id);
        map.put("parentId", null);
        return baseMapper.selectShowMenuByUser(map);
    }

    @Override
    public List<Menu> selectAllMenus(Map<String, Object> map) {
        return baseMapper.getMenus(map);
    }

    @Override
    public List<Menu> selectAllMenuList(Map<String, Object> map) {
        return baseMapper.selectByMap(map);
    }

    @Override
    public Menu selectById(Integer parentId) {
        return baseMapper.selectById(parentId);
    }

    @Override
    public Integer getCountByName(String name) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("del_flag", false);
        wrapper.eq("name", name);
        return baseMapper.selectCount(wrapper).intValue();
    }

    @Override
    public Integer getCountByPermission(String permission) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("del_flag", false);
        wrapper.eq("permission", permission);
        return baseMapper.selectCount(wrapper).intValue();
    }

    @Override
    public Integer selectFirstLevelMenuMaxSort() {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        Menu o = getOne(wrapper.select("max(sort) as sort").isNull("parent_id"));
        return o == null ? 1 : o.getSort() + 1;
    }

    @Override
    public Integer seleclMenuMaxSortByPArentId(Integer parentId) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        Menu o = getOne(wrapper.select("max(sort) as sort").eq("parent_id", parentId));
        return o == null ? 1 : o.getSort() + 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateMenu(Menu menu) {
        saveOrUpdate(menu);
    }

}
